// $(function(){
var previewForUeditor = function() {
	// 获取参数
	var topUtil = cmedit.global;
	var mainGuid = "";
	var clbGuid = "";
	var tenantId = "";
	var token = "";
	var userId = "";
	var userName = "";
	var currentPage = 1;
	var pageSize = 5;
	var editorDemo = '';
	var setWidthHeight = function(ImgD, screenWidth) {// 参数(图片,允许的宽度,允许的高度)
		var iwidth = 970;
		var iheight = 2000;
		var src = $(ImgD).attr("src");
		var imgwidth = $(ImgD).outerWidth();
		var imgheight = $(ImgD).outerHeight();
		if(imgwidth>0 && imgheight>0){
			if(imgwidth/imgheight>= iwidth/iheight){
				if(imgwidth>iwidth){
					$(ImgD).attr("width", iwidth+"px");
					$(ImgD).attr("height",((imgheight*iwidth)/imgwidth)+"px");
				}else{
					$(ImgD).attr("width", imgwidth+"px");
					$(ImgD).attr("height", imgheight+"px");
				}
			}else{
				if(imgheight>iheight){
					$(ImgD).attr("width", ((imgwidth*iheight)/imgheight)+"px");
					$(ImgD).attr("height", iheight+"px");
				}else{
					$(ImgD).attr("width", imgwidth+"px");
					$(ImgD).attr("height", imgheight+"px");
				}
			}
		}
	};
	/**
	 * 图片加载失败方法
	 * 
	 * @param imgObj
	 */
	var getFail = function(imgObj, manuscripttype) {
		var screenWidth = $(window).width();
		$(imgObj).attr('alt', '');
		if (screenWidth < 500) {
			$(imgObj).css('width', screenWidth * 0.92);
			$(imgObj).css('height', screenWidth * 0.92);
		} else {
			if (manuscripttype == 1) {
				$(imgObj).css('width', '100%');
				$(imgObj).css('height', $(imgObj).outerWidth());
			} else {
				$(imgObj).css('width', '440px');
				$(imgObj).css('height', '440px');
			}
		}
	};
	return {
		init: function() {
			c = this;
			try{
				//发布预览
				var url = window.parent.document.getElementById("previewIframe").contentWindow.location.search
				mainGuid = topUtil.getParameterFromByUrl("mainGuid",url);
				tenantId = topUtil.getParameterFromByUrl("tenantId",url);
				token = topUtil.getParameterFromByUrl("token",url);
				userId = topUtil.getParameterFromByUrl("userId",url);
				userName = topUtil.getParameterFromByUrl("userName",url);
				clbGuid = topUtil.getParameterFromByUrl("clbGuid",url);
			}catch(e){
				//通过微信二维码预览
				mainGuid = topUtil.getParameterFromUrl("mainGuid");
				tenantId = topUtil.getParameterFromUrl("tenantId");
				token = topUtil.getParameterFromUrl("token");
				userId = topUtil.getParameterFromUrl("userId");
				userName = topUtil.getParameterFromUrl("userName");
				clbGuid = topUtil.getParameterFromUrl("clbGuid");
			}
			editorDemo = $("#editor").html();
			c.initData();
			c.initComments();
			c.initEditor();
			c.initEvent();
		},
		deleteComment :function(id){
			var postData = {
					commentGuid : id
			}
			$.ajax({
				type: "post",
				async: true,
				dataType: "json",
				url: cmedit.global.cmsPath + "CommentController/deleteComment",
				data: postData,
				beforeSend: function(XHR) {
					XHR.setRequestHeader("token", token);
					XHR.setRequestHeader("tenantId", tenantId);
					XHR.setRequestHeader("userId", userId);
					XHR.setRequestHeader("userName", userName);
				},
				success: function (data) {
					if (data.status) {						
						currentPage = 1;
                    	c.initComments();
                    	$("#editor").html(editorDemo); 
					} else {
						console.log(data);
					}
				}
			});
		},
		initData: function() {
			$.ajax({
				type: "post",
				async: true,
				dataType: "json",
				url: cmedit.global.cmsPath + "CmsController/getWebManuscriptByGuid",
				data: {
					"mainGuid" : mainGuid,
					"tenantId" : tenantId
				},
				beforeSend: function(XHR) {
					XHR.setRequestHeader("token", token);
					XHR.setRequestHeader("tenantId", tenantId);
				},
				success: function (data) {
					if (data.status) {
						// 渲染稿件信息
						var manuscript = data.data;
						console.log("manuscript:",manuscript);
						$("#article_title").html(manuscript.mainHeader);
						$("#author").html(manuscript.mainCreateUserName); 
						$("#columnName").html(cmedit.global.isNotEmpty(manuscript.mainColumnName) ? manuscript.mainColumnName : "无"); 
						$("#createtime").html(manuscript.mainCreateTime);
						$("#totalWords").html(manuscript.mainTextContent.length+'字');
						$("#webContent").html(manuscript.cmsH5Content);
						if(manuscript.mainIsOriginal == 1){
							$("#mainSources").html("原创");
						}else{
							$("#mainSources").html(cmedit.global.isNotEmpty(manuscript.mainSources) ? manuscript.mainSources : "转载");	
						}
						if(cmedit.global.isNotEmpty(manuscript.cmsSourceUrl)){
							// $(".original-title").css('display','block');
							$("#sourceUrl").html(manuscript.cmsSourceUrl);
							$("#sourceUrl").attr("href",manuscript.cmsSourceUrl);
						}
						$("#article_content").html(manuscript.cmsH5Content);						
					} else {
						console.log(data);
					}
				}
			});
		},
		initComments: function(refresh) {
			var postData = {
				currentPage : currentPage,
				pageSize : pageSize,
				mainGuid : mainGuid
			}
			$.ajax({
				type: "post",
				async: true,
				dataType: "json",
				url: cmedit.global.cmsPath + "CommentController/getCommentByPage",
				data: postData,
				beforeSend: function(XHR) {
					XHR.setRequestHeader("token", token);
					XHR.setRequestHeader("tenantId", tenantId);
					XHR.setRequestHeader("userId", userId);
					XHR.setRequestHeader("userName", userName);
				},
				success: function (data) {
					if (data.status) {
						$("#comment_cont").html(data.data.totalCount+"条");
						var comments = data.data.list;
						for(var i=0;i<comments.length;i++){
							comments[i].commentTime = c.formaterTime(comments[i].commentTime);
							comments[i].currentUserId = userId;
						}
						var html = template("commentList_html", data.data);
						$("#all_comments_list").html(html);
						if(!refresh){
							c.initPage(data.data.totalPage);
						}
					} else {
						console.log(data);
					}
				}
			});
		},
		// 格式化时间
		formaterTime: function(time) {
			var formTime = time;
			var dateBegin = new Date(time.replace(/-/g, "/"));//将-转化为/，使用new Date
			var dateEnd = new Date();//获取当前时间
			var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
			var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
			var dayoff = dateBegin.getDate() - dateEnd.getDate();
			if(dayDiff <2 &&dayoff == 1){
				formTime = "昨天";
				return formTime;
			}
			if(dayDiff <2 &&dayoff == 0){
				var leave1=dateDiff%(24*3600*1000)    //计算天数后剩余的毫秒数
				var hours=Math.floor(leave1/(3600*1000))//计算出小时数
				if(hours>0){
					formTime = hours+"小时之前";
					return formTime;
				}
				//计算相差分钟数
				var leave2=leave1%(3600*1000)    //计算小时数后剩余的毫秒数
				var minutes=Math.floor(leave2/(60*1000))//计算相差分钟数
				if(minutes>0){
					formTime = minutes+"分钟之前";
					return formTime;
				}
				//计算相差秒数
				var leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
				var seconds=Math.round(leave3/1000);
				formTime = seconds+"秒钟之前";
				
			}
			return formTime;			
		},
		/**
         * 初始化分页数据
         */
        initPage: function(totalPage) {
        	$("#pagination").html("");
        	$("#pagination").html("<div class='m-pagination'></div>");
            $(".m-pagination").whjPaging({
                pageSizeOpt: [
                    { 'value': 5, 'text': '5', 'selected': true },
                    { 'value': 10, 'text': '10' },
                    { 'value': 15, 'text': '15' },
                    { 'value': 20, 'text': '20' }
                ],
                totalPage: totalPage,
                showPageNum: 5,
                /* firstPage: '<a href="javascript:void(0)">«</a>',
                previousPage: '<a href="javascript:void(0)">‹</a>',
                nextPage: '<a href="javascript:void(0)">›</a>',
				lastPage: '<a href="javascript:void(0)">»</a>', */
				previousPage: '<i class="icon iconfont iconshangyiye"></i>',
                nextPage: '<i class="icon iconfont iconxiayiye"></i>',
                skip: '',
                confirm: 'Go',
                refresh: 'refresh',
                totalPageText: '共 {} 条记录',
                isShowFL: false,
                isShowPageSizeOpt: true,
                isShowSkip: true,
                isShowRefresh: false,
                // isShowTotalPage: false,
                isResetPage: false,
                callBack: function(currPage, _pageSize) {
                    currentPage = currPage;
                    pageSize = _pageSize;
                    c.initComments("refresh");
                }
            });
        },
		initEditor: function() {
	        $("#editor").emoji({
        		button: "#btn",
                showTab: true,
                animation: 'fade',
                icons: [{
                    name: "默认",
                    path: "../../static/plugins/emoji/img/tieba/",
                    maxNum: 50,
                    file: ".jpg",
                    placeholder: ":{alias}:",
                    alias: {
                        1: "hehe",
                        2: "haha",
                        3: "tushe",
                        4: "a",
                        5: "ku",
                        6: "lu",
                        7: "kaixin",
                        8: "han",
                        9: "lei",
                        10: "heixian",
                        11: "bishi",
                        12: "bugaoxing",
                        13: "zhenbang",
                        14: "qian",
                        15: "yiwen",
                        16: "yinxian",
                        17: "tu",
                        18: "yi",
                        19: "weiqu",
                        20: "huaxin",
                        21: "hu",
                        22: "xiaonian",
                        23: "neng",
                        24: "taikaixin",
                        25: "huaji",
                        26: "mianqiang",
                        27: "kuanghan",
                        28: "guai",
                        29: "shuijiao",
                        30: "jinku",
                        31: "shengqi",
                        32: "jinya",
                        33: "pen",
                        34: "aixin",
                        35: "xinsui",
                        36: "meigui",
                        37: "liwu",
                        38: "caihong",
                        39: "xxyl",
                        40: "taiyang",
                        41: "qianbi",
                        42: "dnegpao",
                        43: "chabei",
                        44: "dangao",
                        45: "yinyue",
                        46: "haha2",
                        47: "shenli",
                        48: "damuzhi",
                        49: "ruo",
                        50: "OK"
                    },
                    title: {
                        1: "呵呵",
                        2: "哈哈",
                        3: "吐舌",
                        4: "啊",
                        5: "酷",
                        6: "怒",
                        7: "开心",
                        8: "汗",
                        9: "泪",
                        10: "黑线",
                        11: "鄙视",
                        12: "不高兴",
                        13: "真棒",
                        14: "钱",
                        15: "疑问",
                        16: "阴脸",
                        17: "吐",
                        18: "咦",
                        19: "委屈",
                        20: "花心",
                        21: "呼~",
                        22: "笑脸",
                        23: "冷",
                        24: "太开心",
                        25: "滑稽",
                        26: "勉强",
                        27: "狂汗",
                        28: "乖",
                        29: "睡觉",
                        30: "惊哭",
                        31: "生气",
                        32: "惊讶",
                        33: "喷",
                        34: "爱心",
                        35: "心碎",
                        36: "玫瑰",
                        37: "礼物",
                        38: "彩虹",
                        39: "星星月亮",
                        40: "太阳",
                        41: "钱币",
                        42: "灯泡",
                        43: "茶杯",
                        44: "蛋糕",
                        45: "音乐",
                        46: "haha",
                        47: "胜利",
                        48: "大拇指",
                        49: "弱",
                        50: "OK"
                    }
                }, {
                	name: "QQ",
                    path: "../../static/plugins/emoji/img/qq/",
                    maxNum: 91,
                    excludeNums: [41, 45, 54],
                    file: ".gif",
                    placeholder: "#qq_{alias}#"
                }]
            });
            
		},
		initEvent: function() {
			$("#editor").on("focus",function(e){
				if(this.innerHTML == editorDemo){
					this.innerHTML = "";
				}
			});
			$("#editor").on("blur",function(e){
				if(this.innerHTML == "" || this.innerHTML == "<br>"){
					this.innerHTML = editorDemo;
				}
			});
			$("#make_comments").on("click", function(){
				var context = $("#editor").text();
				var contextHtml = $("#editor").html();
				if(contextHtml == editorDemo || contextHtml == "" || contextHtml == "<br>" || context == ""){
					$.notify("请先输入文字评论");
					return;
				}else{
					c.makeComments();
				}
			});
	            
		},
		makeComments: function() {
			var commentTextContent = $("#editor").text();
			var commentH5Content = $("#editor").html();
			var postData = {
				commentUserId : userId,
				commentUserName : userName,
				mainGuid : mainGuid,
				clbGuid : clbGuid,
				commentTextContent : commentTextContent,
				commentH5Content : commentH5Content
			}
			$.ajax({
				type: "post",
				async: true,
				dataType: "json",
				url: cmedit.global.cmsPath + "CommentController/putOrPostComment",
				data: postData,
				beforeSend: function(XHR) {
					XHR.setRequestHeader("token", token);
					XHR.setRequestHeader("tenantId", tenantId);
					XHR.setRequestHeader("userId", userId);
					XHR.setRequestHeader("userName", userName);
				},
				success: function (data) {
					if (data.status) {						
						currentPage = 1;
                    	c.initComments();
                    	$("#editor").html(editorDemo); 
					} else {
						console.log(data);
					}
				}
			});
		},

	}
}();
$(function() {
    previewForUeditor.init();
});